package com.young.springboot.kafka;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @description：
 * @author: yangyahui01
 * @date: 12/5/24 2:47 PM
 */
public class Utils {
    protected static String localIp() {
        InetAddress address = hostAddress();
        return address == null ? "127.0.0.1" : address.getHostName();
    }

    protected static String hostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }

    private static String getHostName() {
        return hostName();
    }

    private static InetAddress hostAddress() {
        try {
            InetAddress localAddress = InetAddress.getLocalHost();
            if (checkAddress(localAddress)) {
                return localAddress;
            }
        } catch (Throwable e) {
            //
        }
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces == null) {
                return null;
            }
            while (interfaces.hasMoreElements()) {
                try {
                    NetworkInterface network = interfaces.nextElement();
                    Enumeration<InetAddress> addresses = network.getInetAddresses();
                    if (addresses == null) {
                        continue;
                    }
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (checkAddress(address)) {
                            return address;
                        }
                    }
                } catch (Throwable e) {
                    //
                }
            }
        } catch (Throwable e) {
            //
        }
        return null;
    }

    private static boolean checkAddress(InetAddress address) {
        //只获取172.，192.，10.域IP
        if (address != null
                && !address.isLoopbackAddress()
                && address.isSiteLocalAddress()
                && (address instanceof Inet4Address)) {
            return true;
        }

        return false;
    }
}
